<template>
  <div class="orders-container">
    <el-card class="orders-card">
      <template #header>
        <div class="orders-header">
          <h2 class="orders-title">我的订单</h2>
          <div class="sort-controls">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
              <el-option label="创建时间（最新）" value="createTime-desc" />
              <el-option label="创建时间（最早）" value="createTime-asc" />
              <el-option label="完成时间（最新）" value="tradeTime-desc" />
              <el-option label="完成时间（最早）" value="tradeTime-asc" />
              <el-option label="价格（高到低）" value="price-desc" />
              <el-option label="价格（低到高）" value="price-asc" />
            </el-select>
          </div>
        </div>
      </template>
      
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="orders.length === 0" class="empty-state">
        <el-empty description="暂无订单" />
      </div>
      
      <div v-else class="orders-list">
        <el-card
          v-for="order in orders"
          :key="order.id"
          class="order-item"
        >
          <div class="order-header">
            <span class="order-no">订单号：{{ order.code || order.id }}</span>
            <el-tag :type="getStatusType(order.tradeStatus)">
              {{ getStatusText(order.tradeStatus) }}
            </el-tag>
          </div>
          
          <div class="order-content">
            <el-image
              :src="getProductImage(order.coverList)"
              class="product-image"
              fit="cover"
              :preview-src-list="getProductImages(order.coverList)"
            />
            <div class="product-info">
              <h3 class="product-name">{{ order.productName }}</h3>
              <div class="product-owner">
                <span class="owner-label">卖家：</span>
                <span class="owner-name">{{ maskUserName(order.userName || '未知用户') }}</span>
              </div>
              <div class="order-details">
                <p>交易金额：¥{{ order.buyPrice }}</p>
                <p>交易详情：{{ order.detail || '暂无详情' }}</p>
              </div>
            </div>
          </div>
          
          <div class="order-footer">
            <span class="order-time">下单时间：{{ formatTime(order.createTime) }}</span>
            <span class="trade-time" v-if="order.tradeTime">交易时间：{{ formatTime(order.tradeTime) }}</span>
                         <div class="order-actions">
               <el-button
                 size="small"
                 @click="handleViewDetail(order)"
               >
                 查看详情
               </el-button>
               <!-- 为待收货状态的订单添加确认收货按钮 -->
               <el-button
                 v-if="!order.tradeStatus"
                 type="primary"
                 size="small"
                 @click="handleConfirmReceipt(order)"
                 :loading="payingOrderId === order.id"
               >
                 确认收货
               </el-button>
               <!-- 为已完成订单添加删除按钮 -->
               <el-button
                 v-if="order.tradeStatus"
                 type="danger"
                 size="small"
                 @click="handleDeleteOrder(order)"
               >
                 删除订单信息
               </el-button>
             </div>
          </div>
        </el-card>
      </div>
      
             <div v-if="total > 0" class="pagination-wrapper">
         <el-pagination
           v-model:current-page="currentPage"
           v-model:page-size="pageSize"
           :page-sizes="[10, 20, 50, 100]"
           :total="total"
           layout="total, sizes, prev, pager, next, jumper"
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
         />
       </div>
     </el-card>
   </div>

   <!-- 商品详情模态框 -->
   <el-dialog
     v-model="detailDialogVisible"
     title="商品详情"
     width="800px"
     :before-close="handleCloseDetailDialog"
   >
     <div v-if="selectedProduct" class="product-detail-modal">
       <div class="product-images">
         <el-image
           :src="getProductImage(selectedProduct.coverList)"
           fit="cover"
           class="main-image"
           :preview-src-list="getProductImages(selectedProduct.coverList)"
         />
       </div>
       
       <div class="product-info-detail">
         <h2 class="product-title">{{ selectedProduct.name }}</h2>
         
         <div class="product-meta">
           <div class="meta-item">
             <span class="label">价格：</span>
             <span class="value price">¥{{ selectedProduct.price }}</span>
           </div>
           <div class="meta-item">
             <span class="label">库存：</span>
             <span class="value">{{ selectedProduct.inventory }}件</span>
           </div>
           <div class="meta-item">
             <span class="label">成色：</span>
             <span class="value">{{ getOldLevelText(selectedProduct.oldLevel) }}</span>
           </div>
           <div class="meta-item">
             <span class="label">可砍价：</span>
             <span class="value">
               <el-tag :type="selectedProduct.isBargain ? 'success' : 'info'" size="small">
                 {{ selectedProduct.isBargain ? '是' : '否' }}
               </el-tag>
             </span>
           </div>
         </div>
         
         <div class="product-description">
           <h3>商品描述</h3>
           <p>{{ selectedProduct.detail || '暂无描述' }}</p>
         </div>
         
         <div class="product-owner-info">
           <h3>卖家信息</h3>
           <p>卖家：{{ maskUserName(selectedProduct.userName || selectedProduct.userAccount || '未知用户') }}</p>
         </div>
         
         <div class="product-time">
           <p>发布时间：{{ formatTime(selectedProduct.createTime) }}</p>
         </div>
       </div>
     </div>
     
     <template #footer>
       <span class="dialog-footer">
         <el-button @click="handleCloseDetailDialog">关闭</el-button>
       </span>
     </template>
   </el-dialog>
 </template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'
import { getOldLevelText, maskUserName } from '@/utils/product'
import request from '@/utils/request'

const router = useRouter()
const productStore = useProductStore()
const userStore = useUserStore()

const orders = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 支付相关
const payingOrderId = ref<number | null>(null)

// 排序相关
const sortBy = ref('createTime-desc') // 默认按创建时间倒序

// 模态框相关
const detailDialogVisible = ref(false)
const selectedProduct = ref<any>(null)
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const getProductImage = (coverList: string) => {
  try {
    if (!coverList) return '/placeholder.svg'

    return coverList  ? coverList : '/placeholder.svg'
  } catch {
    return '/placeholder.svg'
  }
}

const getProductImages = (coverList: string) => {
  try {
    if (!coverList) return ['/placeholder.svg']
    const images = JSON.parse(coverList)
    return images && images.length > 0 ? images : ['/placeholder.svg']
  } catch {
    return ['/placeholder.svg']
  }
}



const getStatusType = (tradeStatus: boolean) => {
  return tradeStatus ? 'success' : 'warning'
}

const getStatusText = (tradeStatus: boolean) => {
  return tradeStatus ? '已完成' : '待收货'
}

const loadOrders = async () => {
  try {
    loading.value = true
    
    // 检查用户是否已登录
    if (!userStore.user || !userStore.user.username) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    const result = await productStore.getUserOrders({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: userStore.user.username,
      sortBy: sortBy.value // 传递排序参数
    })
    
    orders.value = result.list
    total.value = result.total
  } catch (error: any) {
    console.error('获取订单列表失败:', error)
    if (error.message && error.message.includes('用户没有订单')) {
      orders.value = []
      total.value = 0
    } else {
      ElMessage.error('获取订单列表失败')
    }
  } finally {
    loading.value = false
  }
}



const handleViewDetail = async (order: any) => {
  try {
    // 获取商品详情
    const productDetail = await productStore.getProductDetail(order.productId)
    if (productDetail) {
      // 将商品详情转换为any类型以便添加卖家信息
      const productWithSeller = productDetail as any
      
      // 如果商品详情中没有卖家信息，则从订单中获取
      if (!productWithSeller.userName && !productWithSeller.userAccount) {
        productWithSeller.userName = order.userName
        productWithSeller.userAccount = order.userAccount
      }
      
      // 如果仍然没有卖家信息，尝试通过用户ID获取
      if (!productWithSeller.userName && !productWithSeller.userAccount && productWithSeller.userId) {
        try {
          const userInfo = await userStore.getUserById(productWithSeller.userId)
          if (userInfo) {
            productWithSeller.userName = userInfo.userName
            productWithSeller.userAccount = userInfo.userAccount
          }
        } catch (userError) {
          console.error('获取卖家信息失败:', userError)
        }
      }
      
      selectedProduct.value = productWithSeller
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 处理订单确认收货
const handleConfirmReceipt = async (order: any) => {
  try {
    payingOrderId.value = order.id
    
    // 创建确认收货对话框
    const { value: formValues } = await ElMessageBox.prompt(
      '请填写收货评价（可选）：',
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入收货评价，如：商品质量很好，包装完整...',
        inputValue: order.detail || '',
        inputValidator: (value) => {
          if (value && value.length > 500) {
            return '评价内容不能超过500字'
          }
          return true
        }
      }
    )
    
    // 调用完成订单API
    const response = await productStore.completeOrder({
      detail: formValues || '',
      code: order.code || order.id.toString()
    })
    
    if (response.data) {
      ElMessage.success('收货成功！')
      // 重新加载订单列表
      await loadOrders()
      
      // 通知父组件刷新统计数据
      const parentComponent = getCurrentInstance()?.parent
      if (parentComponent && parentComponent.exposed?.refreshStats) {
        parentComponent.exposed.refreshStats()
      }
    } else {
      ElMessage.error(response.data?.message || '收货失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      // 用户取消收货
      return
    }
    console.error('收货失败:', error)
    ElMessage.error(error.response?.data?.message || '收货失败，请重试')
  } finally {
    payingOrderId.value = null
  }
}

// 删除订单
const handleDeleteOrder = async (order: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单"${order.productName}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除订单API
    const response = await request.delete(`/orders/${order.id}`)
    
    if (response) {
      ElMessage.success('删除成功')
      // 重新加载订单列表
      await loadOrders()
      
      // 通知父组件刷新统计数据
      const parentComponent = getCurrentInstance()?.parent
      if (parentComponent && parentComponent.exposed?.refreshStats) {
        parentComponent.exposed.refreshStats()
      }
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const handleSortChange = () => {
  currentPage.value = 1 // 排序时重置到第一页
  loadOrders()
}

const handleCloseDetailDialog = () => {
  detailDialogVisible.value = false
  selectedProduct.value = null
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadOrders()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadOrders()
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped lang="scss">
.orders-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.orders-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  :deep(.el-card__header) {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    color: white;
    border-radius: 12px 12px 0 0;
  }
}

.orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.orders-title {
  text-align: center;
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  
  .el-select {
    min-width: 160px;
  }
}

.loading-state {
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.orders-list {
  .order-item {
    margin-bottom: 16px;
    border-radius: 8px;
    overflow: hidden;
    transition: transform 0.2s, box-shadow 0.2s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px 16px 12px;
  border-bottom: 1px solid #e8e8e8;
  
  .order-no {
    font-weight: bold;
    color: #2c3e50;
    font-size: 14px;
  }
}

.order-content {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  padding: 0 16px;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  margin: 0 0 8px;
  color: #2c3e50;
  font-weight: 600;
}

.product-owner {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.owner-label {
  color: #999;
}

.owner-name {
  color: #409eff;
  font-weight: 500;
}

.order-details {
  p {
    margin: 4px 0;
    color: #7f8c8d;
    font-size: 14px;
  }
}

.product-tags {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 16px;
  border-top: 1px solid #e8e8e8;
  
  .order-time {
    color: #7f8c8d;
    font-size: 14px;
  }
  
  .trade-time {
    color: #7f8c8d;
    font-size: 14px;
    margin-left: 20px;
  }
  
  .order-actions {
    display: flex;
    gap: 8px;
    
         /* 确认收货按钮特殊样式 */
     .el-button--primary {
       background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
       border: none;
       font-weight: 600;
       transition: all 0.3s ease;
       
       &:hover {
         transform: translateY(-1px);
         box-shadow: 0 4px 12px rgba(76, 175, 80, 0.4);
       }
       
       &:active {
         transform: translateY(0);
       }
     }
     
     /* 删除订单按钮特殊样式 */
     .el-button--danger {
       background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
       border: none;
       font-weight: 600;
       transition: all 0.3s ease;
       
       &:hover {
         transform: translateY(-1px);
         box-shadow: 0 4px 12px rgba(244, 67, 54, 0.4);
       }
       
       &:active {
         transform: translateY(0);
       }
     }
  }
}

.pagination-wrapper {
  margin-top: 30px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .orders-container {
    padding: 15px;
  }
  
  .order-content {
    flex-direction: column;
    gap: 12px;
  }
  
  .product-image {
    width: 100%;
    height: 200px;
  }
  
  .orders-title {
    font-size: 20px;
  }
  
  .order-footer {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
     .order-actions {
     width: 100%;
     justify-content: flex-end;
   }
 }

/* 商品详情模态框样式 */
.product-detail-modal {
  display: flex;
  gap: 24px;
}

.product-images {
  flex: 0 0 300px;
}

.main-image {
  width: 100%;
  height: 300px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info-detail {
  flex: 1;
}

.product-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 16px;
}

.product-meta {
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  
  .label {
    font-weight: 500;
    color: #666;
    min-width: 80px;
  }
  
  .value {
    color: #2c3e50;
    
    &.price {
      color: #e74c3c;
      font-size: 18px;
      font-weight: 600;
    }
  }
}

.product-description,
.product-owner-info,
.product-time {
  margin-bottom: 20px;
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0 0 8px;
  }
  
  p {
    color: #666;
    line-height: 1.6;
    margin: 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-detail-modal {
    flex-direction: column;
    gap: 16px;
  }
  
  .product-images {
    flex: none;
  }
  
  .main-image {
    height: 200px;
  }
}
</style> 